from pywebio.input import *
from pywebio.output import *
from pywebio import start_server
from pywebio.pin import *
from pywebio.session import set_env
import pyperclip


def choose(text):
    # text = input("Please input single choice", type="TEXT")

    # Get the contends according to the format
    title_groups = text.__str__().split("---")
    one_page = []
    # Processing!
    # try:
    for title in title_groups:
        buf = title.split('\n')
        buf = list(filter(None, buf))
        one_page.append(buf[0])  # 标题
        indexes = [int(index) - 1 if index.isdigit() else (ord(index) - ord('A')) for index in
                   buf[-1].split()]  # 多个 index的字符串

        if len(buf[-1].split()) == 1:
            # buf[-1].split 答案列表
            one_page.append("""\n[Choice#random#\n""")
        # 多选
        else:
            one_page.append("""\n[Choice#multi,random#\n""")

        for _ in buf[1:-1]:
            if buf[1:-1].index(_) in indexes:
                one_page.append("* " + _ + "\n")  # True
            else:
                one_page.append("- " + _ + "\n")  # True
        one_page.append(']\n')
    return "".join(one_page)


def main():
    # options=['单选', '多选']
    set_env(title="MarkJi 脚本")
    put_markdown("""
    # Input some texts
    """, lstrip=True)
    # put_select('select', options=options, label='当前模式')
    put_textarea('mul_text', rows=10,
                 placeholder='Please input some formatted texts',
                 code={'mode': 'text'})  # rows (int) – 输入框的最多可显示的文本的行数，内容超出时会显示滚动条

    put_markdown('## Preview')
    while True:
        try:
            change_detail = pin_wait_change('mul_text')

            with use_scope('md', clear=True):
                area = choose(change_detail['value'])
                put_text(area)
                put_text()
                put_buttons(['复制内容'], lambda _: pyperclip.copy(area), small=True)
        except:
            with use_scope('md', clear=True):
                put_text("请输入正确格式！")


if __name__ == '__main__':
    start_server(main, debug=True, port=8222, cdn=False)
